import 'dart:async';

import 'dart:io';
import 'dart:typed_data';

import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/9/25.
///
/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/9/25.
///
/// gongzhonghao biglead
/// github https://github.com/zhaolongs
/// bili https://space.bilibili.com/513480210
/// zhihu https://www.zhihu.com/people/zhao-long-90-89
/// csdn https://blog.csdn.net/zl18603543572
/// 西瓜视频 https://www.ixigua.com/home/3662978423
///
///

void main() {
  ///启动根目录
  runApp(MaterialApp(
    home: Example821(),
  ));
}

//在widget中显示
class Example821 extends StatefulWidget {
  @override
  UIImageState createState() => UIImageState();
}


class UIImageState extends State<Example821> {
  Future<File>? _future;

  @override
  void initState() async{
    super.initState();
    //拿到Image对象
    ui.Image image = await getAssetImage('assets/images/loginbg.png');
    //加载本地资源目录图片
    _future = imageAddWaterMark(image);
  }

  //获取资源目录图片 返回ui.Image
  Future<ui.Image> getAssetImage(String asset, {width, height}) async {
    ByteData data = await rootBundle.load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(
      data.buffer.asUint8List(),
      targetWidth: width,
      targetHeight: height,
    );
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

  /// 代码清单 8-12 图片加载水印文字
  /// lib/code8/example_821_Image_Wart.dart
  Future<File> imageAddWaterMark(ui.Image image) async {

    //图片的宽度与高度
    int width = image.width;
    int height = image.height;

    //拿到Canvas
    ui.PictureRecorder recorder = ui.PictureRecorder();
    Canvas canvas = Canvas(recorder);

    //在Canvas上画Image
    canvas.drawImage(image, const Offset(0, 0), Paint());

    //构建文本
    ui.ParagraphBuilder pb = ui.ParagraphBuilder(ui.ParagraphStyle(
      textAlign: TextAlign.start,
      fontWeight: FontWeight.normal,
      fontStyle: FontStyle.normal,
      fontSize: 30,
    ))
      ..pushStyle(ui.TextStyle(color: Colors.black))
      ..addText('早起的年轻人水印');

    ui.ParagraphConstraints pc =
        ui.ParagraphConstraints(width: width.toDouble());
    ui.Paragraph paragraph = pb.build()..layout(pc);
    //绘制文本
    canvas.drawParagraph(paragraph, const Offset(0, 0));

    ui.Picture picture = recorder.endRecording();
    //合成带水印的Image
    ui.Image img = await picture.toImage(width.toInt(), height.toInt());
    //压缩为ByteData
    ByteData? pngBytes = await img.toByteData(format: ui.ImageByteFormat.png);

    //保存到SD卡上
    final Directory _directory = await getTemporaryDirectory();
    final Directory _imageDirectory =
        await Directory('${_directory.path}/image/').create(recursive: true);
    String _targetPath = _imageDirectory.path;
    String localPath =
        '${_targetPath}_${DateTime.now().millisecondsSinceEpoch}.png';
    File file = File(localPath);
    file.writeAsBytesSync(pngBytes!.buffer.asInt8List());

    return file;
  }

  /// 代码清单 8-11-2 显示图片
  /// lib/code8/example_812_Image.dart
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: buildFutureBuilder(),
      ),
    );
  }

  Widget buildFutureBuilder() {
    return FutureBuilder<File>(
      future: _future,
      builder: (context, snapshot) {
        if (snapshot.data == null) {
          //未加载完成时显示一个加载进度
          return const CircularProgressIndicator();
        } else {
          //加载完成后
          File? image = snapshot.data;
          //绘制图片显示
          return Image.file(image!);
        }
      },
    );
  }
}
